package jee.demo.pro.service.impl;

import jee.demo.pro.app.AppConstant;
import jee.demo.pro.util.CryptUtils;
import jee.demo.pro.dao.UserDAO;
import jee.demo.pro.model.User;
import jee.demo.pro.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.regex.Pattern;

/**
 * Created by Zhen on 2015/4/17.
 */
@Service
public class UserServiceImpl implements UserService {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserDAO dao;

    @Override
    public String login(User o) {

        final String username = o.getUsername();
        final String password = o.getPassword();
        /**
         * 当用户名不合法时, 提示USERNAME_NONEXISTENT, 而不是USERNAME_INVALID
         * 因为数据库中肯定不会存在不合法的用户名，这样可以避免对数据库进行无谓的查询,
         * 注: 这种校验一般放在页面上用js执行
         * 下同
         */
        //if (isInvalidUsername(username)) {
        //    o.addMessage(UserMessage.USERNAME_NONEXISTENT);
        //    return AppConstant.Result.User.LOGIN;
        //}
        // TODO: 完善业务处理过程，提高性能，如尽可能减少数据库查询
        User user = dao.getByUsername(username);
        if (user == null) {
        //    o.addMessage(UserMessage.USERNAME_NONEXISTENT);
            return AppConstant.Result.User.LOGIN;
        }
        if (!user.getPassword().equalsIgnoreCase(CryptUtils.encryptPassword(username, password))) {
            //o.addMessage(UserMessage.PASSWORD_INCORRECT);
            return AppConstant.Result.User.LOGIN;
        }
        //doLogin(user);
        //setLoginCookies(user, Boolean.TRUE.equals(o.getAutologin()));
        ////userEventManager.fireAfterEvent(new UserEvent(o));
        return AppConstant.Result.REDIRECT_ROOT;
    }

    @Transactional
    @Override
    public String register(User o) {
        if (isInvalidUsername(o.getUsername()) || isInvalidPassword(o.getPassword()) ) {
            return AppConstant.Result.User.REGISTER;
        }
        o.setPassword(CryptUtils.encryptPassword(o.getUsername(), o.getPassword()));
        o.setActive(true);
        o.setNickname(o.getUsername());
        o.setOnline(true);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        o.setRegtime(timestamp);
        o.setLatetime(timestamp);
        dao.save(o);
        return AppConstant.Result.REDIRECT_ROOT;
    }

    @Override
    public String logout(User o) {
        return null;
    }

    /**
     * 验证用户名
     *
     * @param username the name of User
     * @return True if username is illegal, otherwise false.
     */
    private boolean isInvalidUsername(String username) {
        return username == null || !Validator.USERNAME.matches(username);
    }

    /**
     * check if the password is invalid
     *
     * @param password user's password
     * @return false if password is null or password's length is not between 6 and 32, otherwise true
     */
    private boolean isInvalidPassword(String password) {
        return password == null || !(6 <= password.length() && password.length() <= 32);
    }

    enum Validator {
        //USERNAME("^\\w+([-+\\._]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"),
        //用户名: 字母开头字母数字下划线组成的4-31位长度的字符串
        USERNAME("^[a-zA-Z]\\w{3,30}$"),
        EMAIL("^\\w+([-+\\._]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"),
        MOBILE("^((13[0-9])|(15[^4,\\d])|(18[0-9]))\\d{8}$"),
        NICKNAME("[-_\\.\\w\\u4e00-\\u9fa5]+"),;

        private Pattern p;

        Validator(String regex) {
            p = Pattern.compile(regex);
        }

        public boolean matches(CharSequence input) {
            return p.matcher(input).matches();
        }
    }
}
